const { formatComponentName } = require('../../src/utils/index')
const fs = require('fs')
const updateDevFile = async (type, name) => {
  return new Promise((resolve, reject) => {
    try {
      const formatName = formatComponentName(name)
      const presetJSONSyntax = '// JSON import'
      const importSyntax = `import { JSON as ${formatName}JSON } from '@/components/${type}/${name}/index.js'\n`
      const presetJSstart = '// js start'
      const presetJSSyntaxEnd = '// js end'
      const pageSrc = './src/pages/index/index.vue'
      let content = fs.readFileSync(pageSrc, 'utf-8')
      const JSONLineIndex = content.indexOf(presetJSONSyntax)
      content = content.slice(0, JSONLineIndex) + importSyntax + content.slice(JSONLineIndex, content.length)
      const JsLineIndex = content.indexOf(presetJSstart)
      const JsEndLineIndex = content.indexOf(presetJSSyntaxEnd)
      const JsonsStr = content.slice(JsLineIndex + presetJSstart.length, JsEndLineIndex).replace(']', `${formatName}JSON,]`)
      content = content.slice(0, JsLineIndex + presetJSstart.length) + JsonsStr + content.slice(JsEndLineIndex, content.length)
      const writeFile = fs.writeFileSync(pageSrc, content, 'utf-8')
      console.log('写入index.vue成功');
      resolve(writeFile)
    } catch (error) {
      reject(error)
    }

  })
}

module.exports = {
  updateDevFile
}